#include <vector>
#include <queue>
using namespace std;
/*
 * @lc app=leetcode.cn id=102 lang=cpp
 *
 * [102] 二叉树的层序遍历
 */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    // 递归的方法
    // vector<vector<int>> res;
    // vector<vector<int>> levelOrder(TreeNode* root) {
    //     dfs(0, root);
    //     return res;
    // }

    // void dfs(int height, TreeNode *r) {
    //     if (!r) return;
    //     if (height == res.size()) {
    //         res.push_back({r->val});
    //     }
    //     else {
    //         res[height].push_back(r->val);
    //     }
    //     dfs(height + 1, r->left);
    //     dfs(height + 1, r->right);
    // }

    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        queue<TreeNode*> q; int child = 0;
        q.push(root); child = 1;
        while (!q.empty()) {
            int t = 0; bool flag = false;
            for (int i = 0; i < child; i++) {
                auto x = q.front(); q.pop();
                if (!x) continue;
                if (!flag)  { res.push_back({x->val}); flag = true;}
                else res.back().push_back(x->val);
                q.push(x->left); q.push(x->right); t += 2;
            }
            child = t;
        }
        return res;
    }
};
// @lc code=end

